//
//  AlertView.m
//  DGGMerchant
//
//  Created by Dwt on 2019/8/28.
//  Copyright © 2019 DGG. All rights reserved.
//

#import "AlertView.h"
#import <Masonry/Masonry.h>
#import "UIView+Extension.h"

#define MARGIN 35
#define DEFAULT_ANIMATION_TIME 0.2
@interface AlertView ()

//内容视图
@property (nonatomic, strong) UIView *contentView;
//图片
@property (nonatomic, strong) UIImageView *imageView;
//标题
@property (nonatomic, strong) UILabel *titleLabel;
//文字描述
@property (nonatomic, strong) UILabel *messageLabel;
//左边按钮
@property (nonatomic, strong) UIButton *cancelButton;
//右边按钮
@property (nonatomic, strong) UIButton *confirmButton;

@end

@implementation AlertView

- (instancetype)init
{
    if (self = [super init]) {
        [self config];
    }
    return self;
}

- (instancetype)initWithFrame:(CGRect)frame
{
    if (self = [super initWithFrame:frame]) {
        [self config];
    }
    return self;
}

- (void)config
{
    _image = nil;
    _title = @"";
    _message = @"";
    _cancelTitle = @"";
    _confirmTitle = @"";//
    _titleColor = [[DLThemeAdapter shareInstance] dynamicColor:CREATCOLORWITHSTRING(@"#333333") darkColor:CREATCOLORWITHSTRING(@"#E0E0E0")];
    _messageColor = [[DLThemeAdapter shareInstance] dynamicColor:CREATCOLORWITHSTRING(@"#333333") darkColor:CREATCOLORWITHSTRING(@"#E0E0E0")];
    _cancelColor = [[DLThemeAdapter shareInstance] dynamicColor:CREATCOLORWITHSTRING(@"#999999") darkColor:CREATCOLORWITHSTRING(@"#868686")];
    _confirmColor = CREATCOLORWITHSTRING(@"#1CBEBC");
    _titleFont = [UIFont fontWithName:@"PingFang-SC-Bold" size:18];
    _messageFont = [UIFont fontWithName:@"PingFangSC-Regular" size:14];
    _cancelFont = [UIFont fontWithName:@"PingFangSC-Regular" size:16];
    _confirmFont = [UIFont fontWithName:@"PingFang-SC-Bold" size:16];
    _duration = 1.5;
}

- (void)showMessage:(NSString *)message
           duration:(NSTimeInterval)duration
{
    self.message = message;
    self.duration = duration;
    
    [self show];
}

- (void)showImage:(NSString *)image
          message:(NSString *)message
         duration:(NSTimeInterval)duration
{
    self.image = image;
    self.message = message;
    self.duration = duration;
    
    [self show];
}

- (void)showImage:(NSString *)image
          message:(NSString *)message
     confirmTitle:(NSString *)confirmTitle
          confirm:(Confirm)confirm
{
    self.image = image;
    self.message = message;
    self.confirmTitle = confirmTitle;
    self.confirmClick = confirm;
    
    [self show];
}

- (void)showImage:(NSString *)image
          message:(NSString *)message
     confirmTitle:(NSString *)confirmTitle
     confirmColor:(UIColor *)confirmColor
          confirm:(Confirm)confirm
{
    self.image = image;
    self.message = message;
    self.cancelTitle = @"取消";
    self.confirmTitle = confirmTitle;
    self.confirmColor = confirmColor;
    self.confirmClick = confirm;
    
    [self show];
}

- (void)showImage:(NSString *)image
            title:(NSString *)title
          message:(NSString *)message
      cancelTitle:(NSString *)cancelTitle
     confirmTitle:(NSString *)confirmTitle
           cancel:(Cancel)cancel
          confirm:(Confirm)confirm
{
    self.image = image;
    self.title = title;
    self.message = message;
    self.cancelTitle = cancelTitle;
    self.confirmTitle = confirmTitle;
    self.cancelClick = cancel;
    self.confirmClick = confirm;
    
    [self show];
}

#pragma mark - 显示
- (void)show
{
    [self setupUI];
    
    self.hidden = NO;
    [UIView animateWithDuration:DEFAULT_ANIMATION_TIME animations:^{
        self.alpha = 1;
        self.contentView.transform = CGAffineTransformIdentity;
    } completion:^(BOOL finished) {
        
    }];
    
    if ([self.cancelTitle isEqualToString:@""] && [self.confirmTitle isEqualToString:@""]) {
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)((self.duration + DEFAULT_ANIMATION_TIME) * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            [self dismiss];
        });
    }
}

- (void)dismiss
{
    [UIView animateWithDuration:DEFAULT_ANIMATION_TIME animations:^{
        self.alpha = 0;
        self.contentView.transform = CGAffineTransformMakeScale(0.001, 0.001);
    } completion:^(BOOL finished) {
        self.hidden = YES;
        [self removeFromSuperview];
    }];
}

#pragma mark - 设置UI
- (void)setupUI
{
    [self.subviews makeObjectsPerformSelector:@selector(removeFromSuperview)];
    self.frame = UIScreen.mainScreen.bounds;
    UIWindow *window = [UIApplication sharedApplication].keyWindow;
    [window addSubview:self];
    [window bringSubviewToFront:self];
    
    [self removeSubviews];
    
    self.backgroundColor = [[UIColor blackColor]colorWithAlphaComponent:0.5];
    self.alpha = 0;
    
    self.imageView.image = [UIImage imageNamed:kDLUIKitImageName(self.image)];
    
    self.titleLabel.textColor = self.titleColor;
    self.titleLabel.text = self.title;
    self.titleLabel.font = self.titleFont;
    
    self.messageLabel.textColor = self.messageColor;
    self.messageLabel.text = self.message;
    self.messageFont = self.messageFont;
    
    self.cancelButton.titleLabel.font = self.cancelFont;
    [self.cancelButton setTitle:self.cancelTitle forState:UIControlStateNormal];
    [self.cancelButton setTitleColor:self.cancelColor forState:UIControlStateNormal];
    
    self.confirmButton.titleLabel.font = self.confirmFont;
    [self.confirmButton setTitle:self.confirmTitle forState:UIControlStateNormal];
    [self.confirmButton setTitleColor:self.confirmColor forState:UIControlStateNormal];
    
    [self addSubview:self.contentView];
    [self.contentView addSubview:self.imageView];
    [self.contentView addSubview:self.titleLabel];
    [self.contentView addSubview:self.messageLabel];
    [self.contentView addSubview:self.cancelButton];
    [self.contentView addSubview:self.confirmButton];
    
    [self setConstraints];
    
    self.contentView.transform = CGAffineTransformMakeScale(0.001, 0.001);
}

#pragma mark - 设置约束
- (void)setConstraints
{
    //相关判断
    CGFloat contentWidth = [self minContentWidth];
    CGFloat contentHeight = 85;
    
    UIImage *image = [UIImage imageNamed:kDLUIKitImageName(self.image)];
    if (image != nil) {
        contentHeight += image.size.height;
    }
    
    if (![self.title isEqualToString:@""]) {
        contentHeight += 18;
    }
    
    if (![self.message isEqualToString:@""]) {
        CGSize size = [self getStringSizeWithString:self.message font:self.messageFont size:CGSizeZero];
        contentHeight += size.height;
        if (size.height > 20) {
            contentWidth = [self maxContentWidth];
        } else {
            [self.messageLabel sizeToFit];
            CGFloat tWidth = self.messageLabel.size.width + 2 * MARGIN;
            contentWidth = tWidth > [self minContentWidth] ? tWidth : [self minContentWidth];
        }
    }
    
    if (![self.cancelTitle isEqualToString:@""] || ![self.confirmTitle isEqualToString:@""]) {
        contentWidth = [self maxContentWidth];
        contentHeight += 50;
    }
    
    [self.contentView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.center.equalTo(self);
        make.height.mas_equalTo(contentHeight);
        make.width.mas_equalTo(contentWidth);
    }];
    
    CGFloat imageH = self.image ? image.size.height : 0;
    [self.imageView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.contentView).offset(20);
        make.centerX.equalTo(self.contentView);
        make.width.height.mas_equalTo(50);
    }];
    
    [self.titleLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(self.contentView).offset(MARGIN);
        make.right.equalTo(self.contentView).offset(-MARGIN);
        if (image) {
            make.top.equalTo(self.contentView).offset(32+50);
        }else{
            make.top.equalTo(self.contentView).offset(MARGIN);
        }
        make.height.mas_equalTo(18);
    }];
    [self.messageLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        if (image) {
            make.top.equalTo(self.titleLabel.mas_bottom).offset(15);
        } else if(![self.title isEqualToString:@""]) {
            make.top.equalTo(self.titleLabel.mas_bottom).offset(15);
        } else {
            make.top.equalTo(self.contentView).offset(MARGIN);
        }
        if(![self.title isEqualToString:@""] && image) {
            make.top.equalTo(self.titleLabel.mas_bottom).offset(15);
        }
        make.left.equalTo(self.contentView).offset(MARGIN);
        make.right.equalTo(self.contentView).offset(-MARGIN);
    }];
    
    CGFloat cancelButtonH = [self.cancelTitle isEqualToString:@""] ? 0 : 50;
    CGFloat cancelButtonW = 0;
    CGFloat confirmButtonH = [self.confirmTitle isEqualToString:@""] ? 0 : 50;
    CGFloat confirmButtonW = 0;
    if (![self.cancelTitle isEqualToString:@""]) {
        cancelButtonW = [self.confirmTitle isEqualToString:@""] ? contentWidth : contentWidth * 0.5;
    }
    
    if (![self.confirmTitle isEqualToString:@""]) {
        confirmButtonW = [self.cancelTitle isEqualToString:@""] ? contentWidth : contentWidth * 0.5;
    }
    
    [self.cancelButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.bottom.equalTo(self.contentView);
        make.width.mas_equalTo(cancelButtonW);
        make.height.mas_equalTo(cancelButtonH);
    }];
    
    [self.confirmButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.right.bottom.equalTo(self.contentView);
        make.width.mas_equalTo(confirmButtonW);
        make.height.mas_equalTo(confirmButtonH);
    }];
    
    //添加两条线
    if (![self.cancelTitle isEqualToString:@""] || ![self.confirmTitle isEqualToString:@""]) {
        UIView *line1 = [UIView new];
        line1.backgroundColor = [[DLThemeAdapter shareInstance] dynamicColor:CREATCOLOR(217, 217, 217,0.65) darkColor:[UIColor colorWithHex:0x3C3C3D]];
        [self.contentView addSubview:line1];
        [line1 mas_makeConstraints:^(MASConstraintMaker *make) {
            make.bottom.equalTo(self.contentView).offset(-50);
            make.height.mas_equalTo(1);
            make.left.right.equalTo(self.contentView);
        }];
    }
    
    if (![self.cancelTitle isEqualToString:@""] && ![self.confirmTitle isEqualToString:@""]) {
        UIView *line2 = [UIView new];
        line2.backgroundColor = [[DLThemeAdapter shareInstance] dynamicColor:CREATCOLOR(217, 217, 217,0.65) darkColor:[UIColor colorWithHex:0x3C3C3D]];
        [self.contentView addSubview:line2];
        
        [line2 mas_makeConstraints:^(MASConstraintMaker *make) {
            make.centerX.bottom.equalTo(self.contentView);
            make.height.mas_equalTo(50);
            make.width.mas_equalTo(1);
        }];
    }
}

#pragma mark —— 获取字符串的宽度
- (CGSize)getStringSizeWithString:(NSString *)string font:(UIFont *)font size:(CGSize)size{
    if (![string isEqualToString:@""]) {
        CGSize maxSize = CGSizeEqualToSize(size, CGSizeZero) ? CGSizeMake([self maxContentWidth] - MARGIN * 2, [self maxContentHeight]) : size;
        CGSize stringSize = [string boundingRectWithSize:maxSize
                                                 options:NSStringDrawingUsesLineFragmentOrigin|NSStringDrawingUsesFontLeading
                                              attributes:@{NSFontAttributeName:font}
                                                 context:nil].size;
        return stringSize;
    }
    return CGSizeZero;
}

- (CGFloat)maxContentWidth
{
    return SCREEN_WIDTH - MARGIN * 2;
}

- (CGFloat)minContentWidth
{
    return 170;
}

- (CGFloat)maxContentHeight
{
    return SCREEN_HEIGHT * 0.5;;
}

- (void)removeSubviews
{
    if (self.subviews.count) {
        for (UIView *view in self.subviews) {
            [view removeFromSuperview];
        }
    }
}

- (void)cancelButtonClick
{
    if (self.cancelClick) {
        self.cancelClick();
    }
    
    [self dismiss];
}

- (void)confirmButtonClick
{
    if (self.confirmClick) {
        self.confirmClick();
    }
    
    [self dismiss];
}


#pragma mark - lazy
- (UIView *)contentView
{
    if (!_contentView) {
        _contentView = [UIView new];
        _contentView.backgroundColor = [[DLThemeAdapter shareInstance] dynamicColor:[UIColor whiteColor] darkColor:[UIColor colorWithHex:0x2D2D2E]];
        _contentView.layer.cornerRadius = 10;
        _contentView.layer.masksToBounds = YES;
    }
    return _contentView;
}

- (UIImageView *)imageView
{
    if (!_imageView) {
        _imageView = [UIImageView new];
        _imageView.contentMode = UIViewContentModeScaleAspectFill;
    }
    return _imageView;
}

- (UILabel *)titleLabel
{
    if (!_titleLabel) {
        _titleLabel = [UILabel new];
        _titleLabel.textAlignment = NSTextAlignmentCenter;
    }
    return _titleLabel;
}

- (UILabel *)messageLabel
{
    if (!_messageLabel) {
        _messageLabel = [UILabel new];
        _messageLabel.textAlignment = NSTextAlignmentCenter;
        _messageLabel.numberOfLines = 0;
    }
    return _messageLabel;
}

- (UIButton *)cancelButton
{
    if (!_cancelButton) {
        _cancelButton = [UIButton new];
        [_cancelButton setBackgroundColor:[[DLThemeAdapter shareInstance] dynamicColor:[UIColor whiteColor] darkColor:[UIColor colorWithHex:0x2D2D2E]]];
        [_cancelButton addTarget:self action:@selector(cancelButtonClick) forControlEvents:UIControlEventTouchUpInside];
    }
    return _cancelButton;
}

- (UIButton *)confirmButton
{
    if (!_confirmButton) {
        _confirmButton = [UIButton new];
        [_confirmButton setBackgroundColor:[[DLThemeAdapter shareInstance] dynamicColor:[UIColor whiteColor] darkColor:[UIColor colorWithHex:0x2D2D2E]]];
        [_confirmButton addTarget:self action:@selector(confirmButtonClick) forControlEvents:UIControlEventTouchUpInside];
    }
    return _confirmButton;
}

/*
// Only override drawRect: if you perform custom drawing.
// An empty implementation adversely affects performance during animation.
- (void)drawRect:(CGRect)rect {
    // Drawing code
}
*/

@end
